package com.chen.springboot.service.Impl.uniapp;

import com.chen.springboot.dto.uniapp.Categories;
import com.chen.springboot.dto.uniapp.Category;
import com.chen.springboot.mapper.uniapp.CategoriesMapper;
import com.chen.springboot.mapper.uniapp.CategoryMapper;
import com.chen.springboot.mapper.uniapp.GoodsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoriesMapper CategoriesMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    //九宫图分类
    public List<Categories> getAllCategories() {
        return CategoriesMapper.findAllCategories();
    }

    public List<Category> getCategoryHierarchy() {
        List<Category> roots = categoryMapper.selectRootCategories();
        for (Category root : roots) {
            root.setImageBanners(categoryMapper.selectImageBanners(root.getId()));

            List<Category> subs = categoryMapper.selectSubCategories(root.getId());
            if (subs == null) subs = Collections.emptyList();

            for (Category sub : subs) {
                sub.setGoods(goodsMapper.selectGoodsByCategoryId(sub.getId()));

                // 不需要返回的字段置空
                sub.setCategories(null);
                sub.setBrands(null);
                sub.setSaleProperties(null);

                // 设置父节点信息
                sub.setParentId(root.getId());
                sub.setParentName(root.getName());
            }
            root.setChildren(subs);

            root.setGoods(null);
            root.setCategories(null);
            root.setBrands(null);
            root.setSaleProperties(null);
            root.setParentId(null);
            root.setParentName(null);
        }
        return roots;
    }
}
